package com.project.base.service.imppl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.base.mapper.CodeMapper;
import com.project.base.service.CodeService;
import com.project.core.auth.CodeDTO;
import com.project.core.entity.Code;
import com.project.core.entity.User;
import com.project.core.util.CommonUtil;
import com.project.core.util.ScoreContext;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

@Service
public class CodeServiceImpl extends ServiceImpl<CodeMapper, Code> implements CodeService {
    public Code select(CodeDTO codeDTO){
        LambdaQueryWrapper<Code> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Code::getCode, codeDTO.getCode());
        Code code = super.getOne(wrapper);
        return code;
    }
    @Override
    public void save(CodeDTO codeDTO) {
        //正常业务,不论是修改还是删除,ID作为参数一定是前端传过来的.不需要传,我要是用postman,id是要作为参数的
     //   User user= ScoreContext.currentUser();
       // Code code=select(codeDTO);
        Code code=new Code();
        try{
            BeanUtils.copyProperties(codeDTO,code);
            if(!Objects.isNull(code.getId())){
//            code.setUpdateBy(user.getId());
//            code.setUpdateTime(LocalDateTime.now());
                //这块应该加个判断,只有管理员才能修改,不是管理员,抛异常
                super.updateById(code);
            }else{
//            code.setCreateBy(user.getId());
//            code.setCreateTime(LocalDateTime.now());
                super.save(code);
            }
        }catch (DuplicateKeyException e){
            String msg = String.format("字典%s 已存在！", code.getCode());
            CommonUtil.throwException(msg, e);
        }
    }

    public void delete(CodeDTO codeDTO){
        //Code code=select(codeDTO);
        Code code=new Code();
        BeanUtils.copyProperties(codeDTO,code);
        if(!Objects.isNull(code.getId())){
            LambdaQueryWrapper<Code> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Code::getId, codeDTO.getId());
            super.remove(wrapper);
        }else{
            //String msg = String.format("字典%s 已存在！", code.getCode());
            CommonUtil.throwException("没有要删除的数据,请查证后在操作", null);

        }


    }
}
